package cn.dlc.com.sys.config.aop;

import cn.dlc.com.biz.log.entity.OperatorLogEntity;
import cn.dlc.com.biz.log.service.OperatorLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * @Author: dlc
 * @Date: 2021/11/29 - 15:26
 */
@Aspect
@Component
public class OperateAdvice {

    @Autowired
    private OperatorLogService operatorLogService;


    // 所有的service.impl里面的任意类的任意方法
    @Around("execution(* cn.dlc.com..service.impl.*.*(..)) && @annotation(operateLog)")
    public Object insertLogAround(ProceedingJoinPoint point, OperateLog operateLog) throws Throwable{

        OperatorLogEntity log = new OperatorLogEntity();
        log.setId(UUID.randomUUID().toString());
        log.setCreateTime(new Date());
        log.setCreateName("小明");

        // 获取当前拦截的类名
        log.setClassName(point.getTarget().getClass().getName());
        // 获取当前拦截的方法
        log.setMethodName(point.getSignature().getName());

        // 获取请求参数
        Object[] args = point.getArgs();

        log.setOperate(operateLog.operate());
        log.setBizModel(operateLog.bizModel());

        // 计算一下时间
        long startTime = System.currentTimeMillis();
        // 放行（没有拦截的东西），
        Object proceed = point.proceed();
        long endTime = System.currentTimeMillis();

        log.setCostTime(endTime - startTime);

        // 获取返回值相关
        if(proceed != null) {
            // 获取返回值类型
            System.out.println("return class name" + proceed.getClass().getName());
            // 获取返回值
            System.out.println("return value " + proceed.toString());
        } else {
            // 返回值类型为Object
            // 返回值为void。
        }

        // 保存日志
        operatorLogService.save(log);

        return proceed;
    }
}
